package ex2.grammars;

import common.exceptions.ParseException;
import ex2.Token;
import fun.grammar.Grammar;
import fun.parser.Tree;
import fun.parser.earley.EarleyParser;
import fun.parser.earley.EarleyState;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 11/22/13
 */
public abstract class AbstractGrammar implements IGrammar {

    private final Grammar impl = new Grammar(getDefinition());

    @Override
    public final Tree constructParseTree(Iterable<Token> tokens) throws ParseException {
        EarleyParser e = new EarleyParser(tokens, impl);
        List<EarleyState> pts = e.getCompletedParses();

        if (pts.size() != 1) {
            throw new ParseException(e.diagnoseError());
        }

        return pts.get(0).parseTree();
    }
}
